#include "device_mutex_locker.h"

#include "../mk_lib/mk_logger.h"

device_mutex_locker::device_mutex_locker(void)
{
	memset(_mutexName, 0, sizeof(_mutexName));
}

device_mutex_locker::~device_mutex_locker(void)
{
	uninit();
}

int device_mutex_locker::init( char * devName, void * lParam )
{
	char			szMutexName[64] = {0};
	strcpy(szMutexName, "Global\\");
	strcat(szMutexName, devName);
	if(_mutex.m_mutex == NULL)
		_mutex.m_mutex = mutex_create();

	if(!_mutex.m_mutex->bInited)
	{
		mutex_init(_mutex.m_mutex, szMutexName);
		strncpy(_mutexName, szMutexName, 256);
	}

	return 0;
}

int device_mutex_locker::lock(long timeOut)
{
	if(_mutex.m_mutex)
	{
		DBG_LOGMSG("device_mutex_locker::lock %s, timeout = %d count = %d", _mutexName, timeOut, _mutex.m_mutex->LockCount);
		mutex_lock(_mutex.m_mutex, timeOut);
	}

	return 0;
}

int device_mutex_locker::unlock()
{
	if(_mutex.m_mutex)
	{
		DBG_LOGMSG("device_mutex_locker::unlock  %s, count = %d", _mutexName, _mutex.m_mutex->LockCount);
		mutex_unlock(_mutex.m_mutex);
	}

	return 0;
}

int device_mutex_locker::uninit()
{
	if(_mutex.m_mutex)
	{
		mutex_destroy(_mutex.m_mutex);
		_mutex.m_mutex = NULL;
	}
	return 0;
}
